# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from collections import deque


class Solution:
    def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        levels = []
        stack = deque([root])

        while stack:
            level = []
            for _ in range(len(stack)):
                node = stack.popleft()
                level.append(node.val)
                if node.left:
                    stack.appendleft(node.left)
                if node.right:
                    stack.appendleft(node.right)

            levels.append(level)

        return levels[::-1]

sum

